/**
 * 饮食记录页面的JavaScript功能
 */

// 当前用户ID（实际应用中应从登录状态获取）
let currentUserId = 1; // 默认用户ID，实际应用中应该从登录状态获取

// 当前选中的日期
let currentDate = new Date();

// 当前选中的饮食记录ID（用于编辑）
let currentDietRecordId = null;

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 初始化日期选择器
    initDatePicker();
    
    // 初始化表单事件
    initFormEvents();
    
    // 加载当天的饮食记录
    loadDietRecordsForDate(currentDate);
    
    // 加载当天的营养摄入统计
    loadNutritionSummary(currentDate);
    
    // 加载食品列表（用于搜索）
    loadFoodItems();
});

/**
 * 初始化日期选择器
 */
function initDatePicker() {
    // 设置当前日期显示
    updateDateDisplay();
    
    // 前一天按钮点击事件
    document.querySelector('.date-selector .prev-day').addEventListener('click', function() {
        currentDate.setDate(currentDate.getDate() - 1);
        updateDateDisplay();
        loadDietRecordsForDate(currentDate);
        loadNutritionSummary(currentDate);
    });
    
    // 后一天按钮点击事件
    document.querySelector('.date-selector .next-day').addEventListener('click', function() {
        currentDate.setDate(currentDate.getDate() + 1);
        updateDateDisplay();
        loadDietRecordsForDate(currentDate);
        loadNutritionSummary(currentDate);
    });
}

/**
 * 更新日期显示
 */
function updateDateDisplay() {
    const dateDisplay = document.querySelector('.date-selector .date-display');
    const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
    
    const year = currentDate.getFullYear();
    const month = currentDate.getMonth() + 1;
    const day = currentDate.getDate();
    const weekday = weekdays[currentDate.getDay()];
    
    dateDisplay.querySelector('h3').textContent = `${year}年${month}月${day}日`;
    dateDisplay.querySelector('p').textContent = weekday;
    
    // 设置日期输入框的默认值
    document.getElementById('meal-date').valueAsDate = new Date(currentDate);
}

/**
 * 初始化表单事件
 */
function initFormEvents() {
    // 添加食品按钮点击事件
    document.getElementById('add-food-item').addEventListener('click', function() {
        addFoodItemInput();
    });
    
    // 表单提交事件
    document.getElementById('diet-record-form').addEventListener('submit', function(e) {
        e.preventDefault();
        saveDietRecord();
    });
}

/**
 * 添加食品输入行
 */
function addFoodItemInput() {
    const container = document.getElementById('food-items-container');
    
    const foodItemDiv = document.createElement('div');
    foodItemDiv.className = 'flex items-center space-x-2 food-item-row';
    
    foodItemDiv.innerHTML = `
        <input type="text" class="form-input flex-grow food-name" placeholder="搜索或输入食品名称" list="food-list">
        <input type="number" class="form-input w-20 food-amount" placeholder="克数" min="1" value="100">
        <button type="button" class="bg-red-500 text-white p-1 rounded hover:bg-red-600 remove-food-item">
            <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
                <path fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd" />
            </svg>
        </button>
    `;
    
    container.appendChild(foodItemDiv);
    
    // 添加删除按钮事件
    foodItemDiv.querySelector('.remove-food-item').addEventListener('click', function() {
        container.removeChild(foodItemDiv);
    });
}

/**
 * 加载食品列表（用于搜索）
 */
async function loadFoodItems() {
    try {
        const foods = await window.apiService.foodAnalysis.getAllFoods();
        
        // 创建datalist元素
        let datalist = document.getElementById('food-list');
        if (!datalist) {
            datalist = document.createElement('datalist');
            datalist.id = 'food-list';
            document.body.appendChild(datalist);
        }
        
        // 清空现有选项
        datalist.innerHTML = '';
        
        // 添加食品选项
        foods.forEach(food => {
            const option = document.createElement('option');
            option.value = food.name;
            option.dataset.id = food.id;
            datalist.appendChild(option);
        });
    } catch (error) {
        console.error('加载食品列表失败:', error);
        showNotification('加载食品列表失败', 'error');
    }
}

/**
 * 保存饮食记录
 */
async function saveDietRecord() {
    try {
        const mealDate = document.getElementById('meal-date').value;
        const mealTime = document.getElementById('meal-time').value;
        const mealType = document.getElementById('meal-type').value;
        const notes = document.getElementById('notes').value;
        
        // 验证必填字段
        if (!mealDate || !mealTime || !mealType) {
            showNotification('请填写所有必填字段', 'error');
            return;
        }

        // 构建日期时间
        const [hours, minutes] = mealTime.split(':');
        const localDate = new Date(mealDate);
        localDate.setHours(parseInt(hours, 10), parseInt(minutes, 10), 0, 0);


        // 创建饮食记录对象
        const dietRecord = {
            consumptionTime: localDate.toISOString(),  // 这会自动转换为 UTC 时间
            mealType: mealType,
            notes: notes
        };
        
        // 如果是编辑现有记录
        if (currentDietRecordId) {
            // 更新现有记录
            const savedRecord = await window.apiService.dietRecord.updateDietRecord(
                currentUserId,
                currentDietRecordId,
                dietRecord
            );
            
            // 添加食品到饮食记录
            const foodItems = document.querySelectorAll('.food-item-row');
            for (const foodItem of foodItems) {
                const foodName = foodItem.querySelector('.food-name').value;
                const foodAmount = parseFloat(foodItem.querySelector('.food-amount').value) || 100;
                
                // 使用食品名称添加食品到饮食记录
                await window.apiService.dietRecord.addFoodItemByName(
                    currentUserId,
                    savedRecord.id,
                    {
                        name: foodName,
                        amount: foodAmount
                    }
                );
            }
        } else {
            // 创建新记录 - 使用新的一次性API
            // 收集所有食品项
            const foodItems = [];
            document.querySelectorAll('.food-item-row').forEach(foodItemRow => {
                const foodName = foodItemRow.querySelector('.food-name').value;
                const foodAmount = parseFloat(foodItemRow.querySelector('.food-amount').value) || 100;
                
                if (foodName && foodName.trim() !== '') {
                    foodItems.push({
                        name: foodName.trim(),
                        amount: foodAmount
                    });
                }
            });
            
            // 检查是否有食品项
            if (foodItems.length === 0) {
                showNotification('请至少添加一种食品', 'error');
                return;
            }
            
            // 一次性创建饮食记录并添加所有食品
            await window.apiService.dietRecord.createDietRecordWithFoodItems(
                currentUserId,
                dietRecord,
                foodItems
            );
        }
        
        // 重置表单
        resetForm();
        
        // 重新加载饮食记录
        loadDietRecordsForDate(currentDate);
        loadNutritionSummary(currentDate);
        
        showNotification('饮食记录保存成功', 'success');
    } catch (error) {
        console.error('保存饮食记录失败:', error);
        showNotification('保存饮食记录失败', 'error');
    }
}

/**
 * 重置表单
 */
function resetForm() {
    document.getElementById('diet-record-form').reset();
    document.getElementById('meal-date').valueAsDate = new Date(currentDate);
    
    // 清空食品列表，只保留一个空行
    const container = document.getElementById('food-items-container');
    container.innerHTML = '';
    addFoodItemInput();
    
    // 重置当前编辑的记录ID
    currentDietRecordId = null;
}

/**
 * 加载指定日期的饮食记录
 * @param {Date} date - 日期
 */
async function loadDietRecordsForDate(date) {
    try {
        // 格式化日期为ISO格式（YYYY-MM-DD）
        const formattedDate = date.toISOString().split('T')[0];
        
        // 获取当天开始和结束时间
        const startDate = formattedDate;
        const endDate = formattedDate;
        
        // 调用API获取饮食记录
        const records = await window.apiService.dietRecord.getUserDietRecordsByDateRange(
            currentUserId,
            startDate,
            endDate
        );
        
        // 按餐食类型分组
        const recordsByMealType = groupRecordsByMealType(records.content || records);
        
        // 渲染饮食记录
        renderDietRecords(recordsByMealType);
    } catch (error) {
        console.error('加载饮食记录失败:', error);
        showNotification('加载饮食记录失败', 'error');
    }
}

/**
 * 按餐食类型分组饮食记录
 * @param {Array} records - 饮食记录数组
 * @returns {Object} - 按餐食类型分组的记录
 */
function groupRecordsByMealType(records) {
    const grouped = {
        BREAKFAST: [],
        LUNCH: [],
        DINNER: [],
        SNACK: []
    };
    
    records.forEach(record => {
        if (record.mealType) {
            grouped[record.mealType].push(record);
        }
    });
    
    return grouped;
}

/**
 * 渲染饮食记录到页面
 * @param {Object} recordsByMealType - 按餐食类型分组的记录
 */
function renderDietRecords(recordsByMealType) {
    const container = document.querySelector('.diet-records-container');
    container.innerHTML = '';
    
    // 餐食类型的中文名称
    const mealTypeNames = {
        BREAKFAST: '早餐',
        LUNCH: '午餐',
        DINNER: '晚餐',
        SNACK: '零食'
    };
    
    // 遍历每种餐食类型
    for (const [mealType, records] of Object.entries(recordsByMealType)) {
        // 如果该餐食类型没有记录，跳过
        if (records.length === 0) continue;
        
        // 创建餐食类型区块
        const mealTypeDiv = document.createElement('div');
        mealTypeDiv.className = 'bg-white p-6 rounded-lg shadow-md mb-6';
        
        // 添加标题和时间
        let headerHTML = `
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-xl font-semibold text-gray-800">${mealTypeNames[mealType]}</h3>
        `;
        
        // 如果有记录，显示第一条记录的时间
        if (records.length > 0) {
            const timeStr = records[0].consumptionTime;
            const recordTime = new Date(timeStr);

            // 获取小时和分钟，小时加8
            let hours = recordTime.getHours() + 8;
            // 如果超过24小时，减去24
            if (hours >= 24) {
                hours -= 24;
            }
            const minutes = recordTime.getMinutes();

            // 格式化时间，确保两位数显示
            const timeDisplay = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`;

            headerHTML += `<span class="text-sm text-gray-500">${timeDisplay}</span>`;
        }

        headerHTML += `</div>`;
        mealTypeDiv.innerHTML = headerHTML;
        
        // 添加食品列表
        const foodItemsDiv = document.createElement('div');
        foodItemsDiv.className = 'space-y-3';
        
        let totalCalories = 0;
        
        // 遍历该餐食类型的所有记录
        records.forEach(record => {
            // 遍历记录中的所有食品
            // 如果记录有卡路里值，使用它
            if (record.calories) {
                totalCalories += record.calories;
            }
            
            record.foodItems.forEach(foodItem => {
                const foodItemDiv = document.createElement('div');
                foodItemDiv.className = 'flex justify-between items-center pb-2 border-b border-gray-100';
                
                // 获取食物数量（默认为100g）
                const amount = foodItem.amount || 100;
                
                // 计算食品项的卡路里
                let calories = record.calories;
                if (foodItem.nutritionInfo && foodItem.nutritionInfo.calories) {
                    // 按照实际食用量计算卡路里
                    calories = (foodItem.nutritionInfo.calories * amount) / 100;
                }
                
                // 主要营养素
                let mainNutrient = '';
                if (foodItem.nutritionInfo) {
                    const protein = foodItem.nutritionInfo.protein ? (foodItem.nutritionInfo.protein * amount) / 100 : 0;
                    const carbs = foodItem.nutritionInfo.carbohydrates ? (foodItem.nutritionInfo.carbohydrates * amount) / 100 : 0;
                    mainNutrient = protein > carbs ?
                        `蛋白质: ${protein.toFixed(1)}g` :
                        `碳水: ${carbs.toFixed(1)}g`;
                }
                
                foodItemDiv.innerHTML = `
                    <div class="flex items-center">
                        <div class="w-10 h-10 bg-gray-200 rounded-lg mr-3">
                            ${foodItem.imageUrl ? `<img src="${foodItem.imageUrl}" alt="${foodItem.name}" class="w-10 h-10 rounded-lg object-cover">` : ''}
                        </div>
                        <div>
                            <p class="font-medium">${foodItem.name}</p>
                            <p class="text-sm text-gray-500">${amount}g</p>
                        </div>
                    </div>
                    <div class="text-right">
                        <p class="font-medium">${Math.round(calories)} kcal</p>
                        <p class="text-sm text-gray-500">${mainNutrient}</p>
                    </div>
                `;
                
                foodItemsDiv.appendChild(foodItemDiv);
            });
            
            // 添加编辑和删除按钮
            const actionsDiv = document.createElement('div');
            actionsDiv.className = 'flex justify-end space-x-2 mt-2';
            actionsDiv.innerHTML = `
                <button class="text-blue-600 hover:text-blue-800 edit-record" data-id="${record.id}">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
                        <path d="M13.586 3.586a2 2 0 112.828 2.828l-.793.793-2.828-2.828.793-.793zM11.379 5.793L3 14.172V17h2.828l8.38-8.379-2.83-2.828z" />
                    </svg>
                </button>
                <button class="text-red-600 hover:text-red-800 delete-record" data-id="${record.id}">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
                        <path fill-rule="evenodd" d="M9 2a1 1 0 00-.894.553L7.382 4H4a1 1 0 000 2v10a2 2 0 002 2h8a2 2 0 002-2V6a1 1 0 100-2h-3.382l-.724-1.447A1 1 0 0011 2H9zM7 8a1 1 0 012 0v6a1 1 0 11-2 0V8zm5-1a1 1 0 00-1 1v6a1 1 0 102 0V8a1 1 0 00-1-1z" clip-rule="evenodd" />
                    </svg>
                </button>
            `;
            
            foodItemsDiv.appendChild(actionsDiv);
        });
        
        mealTypeDiv.appendChild(foodItemsDiv);
        
        // 添加总计
        const totalDiv = document.createElement('div');
        totalDiv.className = 'mt-4 pt-3 border-t border-gray-200 flex justify-between';
        totalDiv.innerHTML = `
            <p class="font-medium">总计</p>
            <p class="font-medium">${Math.round(totalCalories)} kcal</p>
        `;
        
        mealTypeDiv.appendChild(totalDiv);
        container.appendChild(mealTypeDiv);
    }
    
    // 添加编辑和删除事件
    document.querySelectorAll('.edit-record').forEach(button => {
        button.addEventListener('click', function() {
            const recordId = this.dataset.id;
            editDietRecord(recordId);
        });
    });
    
    document.querySelectorAll('.delete-record').forEach(button => {
        button.addEventListener('click', function() {
            const recordId = this.dataset.id;
            deleteDietRecord(recordId);
        });
    });
}

/**
 * 编辑饮食记录
 * @param {string} recordId - 记录ID
 */
async function editDietRecord(recordId) {
    try {
        // 获取记录详情
        const record = await window.apiService.dietRecord.getDietRecordById(currentUserId, recordId);
        
        // 设置当前编辑的记录ID
        currentDietRecordId = recordId;
        
        // 填充表单
        const consumptionTime = new Date(record.consumptionTime);
        
        document.getElementById('meal-date').valueAsDate = consumptionTime;
        document.getElementById('meal-time').value = consumptionTime.toTimeString().substr(0, 5);
        document.getElementById('meal-type').value = record.mealType;
        document.getElementById('notes').value = record.notes || '';
        
        // 清空食品列表
        const container = document.getElementById('food-items-container');
        container.innerHTML = '';
        
        // 添加食品
        record.foodItems.forEach(foodItem => {
            const foodItemDiv = document.createElement('div');
            foodItemDiv.className = 'flex items-center space-x-2 food-item-row';
            
            foodItemDiv.innerHTML = `
                <input type="text" class="form-input flex-grow food-name" value="${foodItem.name}" list="food-list">
                <input type="number" class="form-input w-20 food-amount" value="100" min="1">
                <button type="button" class="bg-red-500 text-white p-1 rounded hover:bg-red-600 remove-food-item">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
                        <path fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd" />
                    </svg>
                </button>
            `;
            
            container.appendChild(foodItemDiv);
            
            // 添加删除按钮事件
            foodItemDiv.querySelector('.remove-food-item').addEventListener('click', function() {
                container.removeChild(foodItemDiv);
            });
        });
        
        // 如果没有食品，添加一个空行
        if (record.foodItems.length === 0) {
            addFoodItemInput();
        }
        
        // 滚动到表单
        document.getElementById('diet-record-form').scrollIntoView({ behavior: 'smooth' });
    } catch (error) {
        console.error('加载饮食记录详情失败:', error);
        showNotification('加载饮食记录详情失败', 'error');
    }
}

/**
 * 删除饮食记录
 * @param {string} recordId - 记录ID
 */
async function deleteDietRecord(recordId) {
    if (confirm('确定要删除这条饮食记录吗？')) {
        try {
            await window.apiService.dietRecord.deleteDietRecord(currentUserId, recordId);
            
            // 重新加载饮食记录
            loadDietRecordsForDate(currentDate);
            loadNutritionSummary(currentDate);
            
            showNotification('饮食记录已删除', 'success');
        } catch (error) {
            console.error('删除饮食记录失败:', error);
            showNotification('删除饮食记录失败', 'error');
        }
    }
}

/**
 * 加载营养摄入统计
 * @param {Date} date - 日期
 */
async function loadNutritionSummary(date) {
    try {
        // 格式化日期为ISO格式（YYYY-MM-DD）
        const formattedDate = date.toISOString().split('T')[0];
        
        // 调用API获取营养摄入比较
        const nutritionData = await window.apiService.dietRecord.compareActualVsRecommendedIntake(
            currentUserId,
            formattedDate
        );
        
        // 获取各餐食类型的营养摄入统计
        const mealNutritionStats = await window.apiService.dietRecord.getMealNutritionStats(
            currentUserId,
            formattedDate
        );
        
        // 更新营养摄入显示
        updateNutritionDisplay(nutritionData);
        
        // 更新各餐食类型的营养摄入显示
        updateMealNutritionDisplay(mealNutritionStats);
    } catch (error) {
        console.error('加载营养摄入统计失败:', error);
        // 使用默认数据
        updateNutritionDisplay({
            actual: {
                calories: 0,
                protein: 0,
                carbohydrates: 0,
                fat: 0
            },
            recommended: {
                calories: 2000,
                protein: 75,
                carbohydrates: 250,
                fat: 65
            }
        });
    }
}

/**
 * 更新各餐食类型的营养摄入显示
 * @param {Object} mealStats - 各餐食类型的营养摄入统计
 */
function updateMealNutritionDisplay(mealStats) {
    // 更新各餐食类型的营养摄入显示
    if (mealStats.BREAKFAST) {
        document.querySelector('.meal-nutrition-summary .breakfast .value').textContent =
            Math.round(mealStats.BREAKFAST.calories || 0) + ' kcal';
        document.querySelector('.meal-nutrition-summary .breakfast .count').textContent =
            `记录数: ${mealStats.BREAKFAST.recordCount || 0}`;
    }
    
    if (mealStats.LUNCH) {
        document.querySelector('.meal-nutrition-summary .lunch .value').textContent =
            Math.round(mealStats.LUNCH.calories || 0) + ' kcal';
        document.querySelector('.meal-nutrition-summary .lunch .count').textContent =
            `记录数: ${mealStats.LUNCH.recordCount || 0}`;
    }
    
    if (mealStats.DINNER) {
        document.querySelector('.meal-nutrition-summary .dinner .value').textContent =
            Math.round(mealStats.DINNER.calories || 0) + ' kcal';
        document.querySelector('.meal-nutrition-summary .dinner .count').textContent =
            `记录数: ${mealStats.DINNER.recordCount || 0}`;
    }
    
    if (mealStats.SNACK) {
        document.querySelector('.meal-nutrition-summary .snack .value').textContent =
            Math.round(mealStats.SNACK.calories || 0) + ' kcal';
        document.querySelector('.meal-nutrition-summary .snack .count').textContent =
            `记录数: ${mealStats.SNACK.recordCount || 0}`;
    }
}

/**
 * 更新营养摄入显示
 * @param {Object} data - 营养摄入数据
 */
function updateNutritionDisplay(data) {
    const actual = data.actual || {};
    const recommended = data.recommended || {};
    
    // 更新卡路里
    document.querySelector('.nutrition-summary .calories .value').textContent = 
        Math.round(actual.calories || 0);
    document.querySelector('.nutrition-summary .calories .target').textContent = 
        `目标: ${Math.round(recommended.calories || 2000)}`;
    
    // 更新蛋白质
    document.querySelector('.nutrition-summary .protein .value').textContent = 
        `${Math.round(actual.protein || 0)}g`;
    document.querySelector('.nutrition-summary .protein .target').textContent = 
        `目标: ${Math.round(recommended.protein || 75)}g`;
    
    // 更新碳水
    document.querySelector('.nutrition-summary .carbs .value').textContent = 
        `${Math.round(actual.carbohydrates || 0)}g`;
    document.querySelector('.nutrition-summary .carbs .target').textContent = 
        `目标: ${Math.round(recommended.carbohydrates || 250)}g`;
    
    // 更新脂肪
    document.querySelector('.nutrition-summary .fat .value').textContent = 
        `${Math.round(actual.fat || 0)}g`;
    document.querySelector('.nutrition-summary .fat .target').textContent = 
        `目标: ${Math.round(recommended.fat || 65)}g`;
}

/**
 * 显示通知
 * @param {string} message - 通知消息
 * @param {string} type - 通知类型（success, error, info）
 */
function showNotification(message, type = 'info') {
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = `fixed top-4 right-4 p-4 rounded-lg shadow-lg z-50 ${
        type === 'success' ? 'bg-green-500' : 
        type === 'error' ? 'bg-red-500' : 
        'bg-blue-500'
    } text-white`;
    
    notification.textContent = message;
    
    // 添加到页面
    document.body.appendChild(notification);
    
    // 3秒后移除
    setTimeout(() => {
        notification.classList.add('opacity-0', 'transition-opacity', 'duration-500');
        setTimeout(() => {
            document.body.removeChild(notification);
        }, 500);
    }, 3000);
}

// 添加API方法
window.apiService.dietRecord.getDietRecordById = (userId, recordId) =>
    apiRequest(`/users/${userId}/diet-records/${recordId}`);

window.apiService.dietRecord.addFoodItemToDietRecord = (userId, dietRecordId, foodItemId) =>
    apiRequest(`/users/${userId}/diet-records/${dietRecordId}/food-items/${foodItemId}`, 'POST');

window.apiService.dietRecord.removeFoodItemFromDietRecord = (userId, dietRecordId, foodItemId) =>
    apiRequest(`/users/${userId}/diet-records/${dietRecordId}/food-items/${foodItemId}`, 'DELETE');

// 获取指定日期范围内的饮食记录
window.apiService.dietRecord.getUserDietRecordsByDateRange = (userId, startDate, endDate) =>
    apiRequest(`/users/${userId}/diet-records/date-range?startDate=${startDate}&endDate=${endDate}`);